
var util = require('../../../utils/util.js')
//获取应用实例
var app = getApp()
Page({
  data: {
   
    updateid:null,
    catogory:null
  },
  onLoad: function (e) {
   
    var that = this;
    
  
    var id1 = e.id;
    if (id1) {
      // 初始化原数据
      wx.showLoading();
      const db = wx.cloud.database()
      db.collection('categories').where({
        _id: id1
      }).get({
        success: function (res) {
       console.log(res)
          wx.hideLoading();
          if (res.data.length > 0) {
            that.setData({
              updateid: res.data[0]._id,
           
              catogory: res.data[0]
            });
          
            return;
          } else {
            wx.showModal({
              title: '提示',
              content: '无法获取数据',
              showCancel: false
            })
          }
        }
      })
      
    }
  },
  bindCancel: function () {
    wx.navigateBack({})
  },
  //保存
  bindSave: function (e) {
    console.log(e)
    
    var that = this;
    var name = e.detail.value.name;
 
    if (e.detail.value.paixu == "") {
      wx.showModal({
        title: '提示',
        content: '请填写排序',
        showCancel: false
      })
      return
    }
    if (name == "") {
      wx.showModal({
        title: '提示',
        content: '请填写分类名',
        showCancel: false
      })
      return
    }
    var paixu = parseInt(e.detail.value.paixu);
   
  
   
    const db = wx.cloud.database()
    if(!that.data.updateid){
        db.collection('categories').add({
          data: {
            name: name,
            paixu:paixu,
            dateAdd:util.formatTime(new Date())
          },
          success: function(res) {
           
            wx.navigateBack({})
          }
        })
   }else{
    debugger
     console.log(that.data.updateid)
    db.collection('categories').doc(that.data.updateid).update({
      data: {
        name: name,
        paixu:paixu,
      },
      success: function(res) {
        console.log(res)
        wx.navigateBack()
      }
    })
   }
  
  },
  deleteAddress: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要删除该分类吗？',
      success: function (res) {
        if (res.confirm) {
          const db = wx.cloud.database()
        
          db.collection('categories').doc(id).remove({
            
            success: function(res) {
              wx.navigateBack({
                delta: 1,
              })
            }
          })
          /**
           * wx.request({
            url: 'https://api.it120.cc/' + app.globalData.subDomain + '/user/shipping-address/delete',
            data: {
              token: wx.getStorageSync('token'),
              id: id
            },
            success: (res) => {
              wx.navigateBack({})
            }
          })
           */
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
})
